import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserInfoByID } from '@/api/user'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      state.userInfo = {}
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    async login(context, data) {
      const res = await login(data)
      context.commit('setToken', res)
      setTimeStamp()
    },
    async getUserInfo(context) {
      const res = await getUserInfo()
      const base = await getUserInfoByID(res.userId)
      const baseres = { ...res, ...base }
      context.commit('setUserInfo', baseres)
      return res
    },
    logout(context) {
      resetRouter()
      context.commit('removeToken')
      context.commit('permission/setRoutes', [], { root: true })
    }
  }
}

